﻿using Microsoft.AspNetCore.Server.Kestrel.Https;
using Serilog;
using Serilog.Events;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;

namespace IDSReferenceToken
{
    public class Program
    {
        public static int Main(string[] args)
        {
            Log.Logger = new LoggerConfiguration()
#if DEBUG
                .MinimumLevel.Debug()
#else
                .MinimumLevel.Information()
#endif
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
                .Enrich.FromLogContext()
                .WriteTo.Async(c => c.File("Logs/logs.txt"))
#if DEBUG
                .WriteTo.Async(c => c.Console())
#endif
                .CreateLogger();

            try
            {
                Log.Information("Starting IDSReferenceToken.HttpApi.Host.");
                CreateHostBuilder(args).Build().Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Host terminated unexpectedly!");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }

        internal static IHostBuilder CreateHostBuilder(string[] args)
        {
            var builder = Host.CreateDefaultBuilder(args);

            return builder.ConfigureWebHostDefaults((webHostBuilder) =>
            {
                webHostBuilder.ConfigureKestrel(serverOptions =>
                {
                    serverOptions.ListenAnyIP(44322, options =>
                    {
                        var baseDir = Path.GetDirectoryName(typeof(IDSReferenceTokenHttpApiHostModule).Assembly.Location)
                            ?? throw new InvalidOperationException("程序集 IDSReferenceTokenHttpApiHostModule 目录为空！");
#if DEBUG

                        var pfxFile = Path.Combine(baseDir, "Assets/Https/certificate-test.pfx");
                        var password = "LANXIAOFANG";
#else
                    var pfxFile = Path.Combine(baseDir, "Assets/Https/certificate.pfx");
                    var password = "LANXIAOFANG";
#endif

                        if (!File.Exists(pfxFile)) throw new InvalidOperationException($"{pfxFile} is not found.");

                        var cert = new X509Certificate2(pfxFile, password);
                        options.UseHttps(cert);
                    });

                    serverOptions.ConfigureHttpsDefaults(listenOptions =>
                    {
                        listenOptions.ClientCertificateMode = ClientCertificateMode.AllowCertificate;
                        listenOptions.SslProtocols = SslProtocols.Tls13 | SslProtocols.Tls12;
                    });
                });
                webHostBuilder.UseStartup<Startup>();
            })
            .UseAutofac()
            .UseSerilog();
        }
    }
}
